<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>异步处理示例</title>
</head>
<body>
<button id="startButton">开始任务</button>
<div id="message"></div>

<script>
    let socket;
    const startButton = document.getElementById('startButton');
    const messageDiv = document.getElementById('message');

    startButton.addEventListener('click', () => {
        // 建立 WebSocket 连接
        socket = new WebSocket('ws://localhost:8080/ws');

        socket.onopen = () => {
            // 发送一个消息给后端，让后端返回 sessionId
            socket.send('getSessionId');
        };

        socket.onmessage = (event) => {
            if (event.data.startsWith('sessionId:')) {
                const sessionId = event.data.split(':')[1];
                // 发送请求开始异步任务
                fetch(`http://localhost:8080/startTask/${sessionId}`)
                    .then(response => response.text())
                    .then(data => {
                        messageDiv.textContent = data;
                        //alert("后台完成！！！！")
                        console.log(111)
                    });
            } else {
                messageDiv.textContent = event.data;
                console.log(222)
                alert("后台完成。。。！！！")
            }
        };

        socket.onclose = () => {
            console.log('WebSocket 连接已关闭');
        };
    });
</script>
</body>
</html>